package com.realgodo.site.service.application;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.hibernate.DefaultEntityManager;

import com.realgodo.site.entity.application.Application;
import com.realgodo.site.entity.dic.Face;
import com.realgodo.site.service.relation.FriendManager;

@Service
@Transactional
public class ApplicationManager extends DefaultEntityManager<Application, Long> {

	@Autowired
	private SessionFactory sessionFactory;

	@Autowired
	private FriendManager friendManager;

	/** 转换表情符号 */
	public static String convert(String content) {
		if (content == null || "".equals(content.trim())) {
			return null;
		}
		String[] str = content.split(Face.START_MARK);
		if (str.length >= 1) {
			content = str[0];
			for (int i = 1; i < str.length; i++) {
				if (str[i].length() > 0 && str[i].indexOf(Face.END_MARK) != -1) {
					content += ("<img src='/static/userfiles/image/face/" + str[i]
							.replaceFirst(Face.END_MARK, "' />"));
				} else {
					content += (Face.START_MARK + str[i]);
				}

			}
		}
		return content;
	}

	public Application getApplication(Long id) {
		Application application = this.get(id);
		if (!Application.class.getName().equals(
				application.getClass().getName())) {
			application = (Application) (sessionFactory.getCurrentSession()
					.load(application.getClasz(), id));
		}
		return application;
	}

	/**
	 * 获取space的好友及自己的服务 ,并返回子类类型
	 * 
	 * @param spaceId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<? extends Application> getFriendAndMyApplications(Long spaceId,
			int maxResult) {
		Session session = sessionFactory.getCurrentSession();
		List<Long> ids = this.friendManager.getFriendSpaceIdList(spaceId);
		String hql = "select o from Application o where o.space.id in ("
				+ spaceId;
		if (null != ids && ids.size() != 0) {
			for (int i = 0; i < ids.size(); i++) {
				hql += ", " + ids.get(i).toString();
			}
		}
		
		hql += " )";
		
		hql += " order by o.pubTime desc";
		Query q = session.createQuery(hql);
		q.setMaxResults(maxResult);
		List<? extends Application> applications = new ArrayList<Application>();
		List<Application> subApplications = new ArrayList<Application>();
		applications = q.list();
		for (Application application : applications) {
			subApplications.add(this.getApplication(application.getId()));
		}

		return subApplications;
	}
}
